<template >
  <div>
    <ul
      class="drop-down-user"
      :class="isAdmin ? 'admin-user' : ''"
      v-if="showDropdrow"
    >
      <li v-if="!isAdmin && limits.indexOf('personal_setting') > -1">
        <div class="li-contain">
          <span class="V7_iconfont V7_iconV7tubiao_gerenshezhi-huaji"></span>通话设备
          <div class="call-type-wrap lable-wrap">
            <span class="drop-span">接听方式:</span>
            <m7Select
              size="mini"
              style="width: 130px"
              v-model="callType"
              placeholder="请选择"
              :options="options"
              @change="changeLoginType"
            ></m7Select>
          </div>
          <div v-if="callType === 'PSTN'">
            <span class="equipment">手机</span>
            <span>{{ getUserMobile }}</span>
          </div>
          <div v-else-if="callType === 'SIP'" class="label-wrap">
            <span class="drop-span">SIP号:</span
            ><m7Select
              size="mini"
              style="width: 130px"
              v-model="sipNumber"
              placeholder="请选择"
              :options="sipArr"
              :defaultProps="{ label: 'number', value: 'number' }"
              @change="changeLoginType"
            ></m7Select>
          </div>
          <div class="autoAnswer-btn" v-else-if="callType === 'WEBRTC'">
            <span class="tit">自动接听:</span>
            <el-switch
              v-model="isAuto"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="autoStateChange"
            >
            </el-switch>
            <!-- <span class="text">{{!isAuto? '开启' : '关闭'}}</span> -->
          </div>
        </div>
      </li>
      <li @click.stop="handleCommand('user')" v-if="!isAdmin">
        <div class="li-contain">
          <span class="V7_iconfont V7_iconV7tubiao_gerenshezhi-shezhi"></span>设置
        </div>
      </li>
      <li @click.stop="handleCommand('signOut')">
        <div class="li-contain">
          <span class="V7_iconfont V7_iconV7tubiao_gerenshezhi-tuichu"></span>退出
        </div>
      </li>
    </ul>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      append-to-body
      top="10%"
      title="是否确定退出当前系统?"
      :visible.sync="logoutVisible"
      width="30%"
    >
      <el-row>
        <el-col :span="24" style="marginBottom: 20px" v-if="isHasWebchatTodoList">
          <span style="color:#fc6c5c">您有未关闭会话</span>，请确认是否退出？
        </el-col>
        <el-col :span="24">
          <el-checkbox
            v-model.trim="form.toAnswerOffline"
            style="font-size: 12px"
            >退出后继续使用当前接听方式接听来电</el-checkbox>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="logoutVisible = false" size="mini">取消</el-button>
        <el-button type="primary" size="mini" @click="logout">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import { storageManager } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { LoginModule } from '@/store/modules/login'
import WebPhoneSdk from '@/utils/webPhoneSdk'
interface SingOut {
  toAnswerOffline: boolean
}
@Component({
  name: 'UserDropdown'
})
export default class UserDropdown extends Vue {
  private $router: any
  private $store: any
  private $getCache: any
  private $message: any
  private showDropdrow: boolean = false // 是否显示下拉
  private callType: string = ''
  private logoutVisible: boolean = false // 退出弹窗
  private isAdmin: boolean = false // 超级管理员或者是计费跳转登录
  private form: SingOut = { toAnswerOffline: true } // 是否离线接听
  private sipNumber: string = '' // 当前座席使用的SIP号
  private sipArr: object[] = [{}]
  private limits = [] // 权限
  private globalConfig: any = []
  private isAuto: boolean = false // 是否自动接听
  private options: object[] = [
    { label: '手机模式', value: 'PSTN' },
    { label: '软电话', value: 'WEBRTC' },
    { label: 'SIP话机', value: 'SIP' }
  ]

  private isHasWebchatTodoList: boolean = false

  private handleCommand (data: string) {
    if (data === 'user') { // 个人信息设置
      this.showDropdrow = false
      this.closeOrShowUserInfoDiv('show')
    } else if (data === 'signOut') { // 退出
      const actionData = { url: '/im-center/action/webchat/queryWebchatSession', method: 'POST', data: { submenu: 'webchat_todo' } }
      CommonModule.publicAction(actionData).then(res => {
        if (res && res.list && res.list.length > 0) {
          this.isHasWebchatTodoList = true
          if (this.globalConfig && this.globalConfig.isSystemExit) {
            this.$message.error('您有未关闭会话，不允许退出')
          } else {
            this.logoutVisible = true
          }
        } else {
          this.isHasWebchatTodoList = false
          this.logoutVisible = true
        }
      })
    }
  }

  private closeOrShowUserInfoDiv (type) { // 个人信息页面是否展示
    const pane = document.getElementById('user_info_div')
    if (pane) {
      type === 'close' ? pane.style.display = 'none' : pane.style.display = 'block'
    }
  }

  private changeLoginType () { // 切换登录方式||绑定sip号码
    const loginType = this.callType
    let loginNumber = ''
    const session = this.$store.state.common.session
    if (loginType === 'SIP') { // 话机模式 || 软电话模式
      loginNumber = this.sipNumber
      // 注销webrtc
      if (this.getWebRtcFun) {
        this.getWebRtcFun.unregister()
        LoginModule.setWebRtcFun(null)
      }
    } else if (loginType === 'WEBRTC') {
      loginNumber = session.user.webrtcSipNumber
      try {
        // 初始化注册webrtc
        const extraConfig: any = session.extra ? session.extra.extraConfig : {}
        const webphone = new WebPhoneSdk({ server: extraConfig.sipRegisterAddress, sip: session.user.webrtcSipNumber, secret: session.user.webrtcSipKey })
        LoginModule.setWebRtcFun(webphone)
      } catch (error) {
        console.log(error)
      }
    } else { // 手机模式取手机号
      loginNumber = session.user.mobile || ''
      if (this.getWebRtcFun) {
        this.getWebRtcFun.unregister()
        LoginModule.setWebRtcFun(null)
      }
      // 注销webrtc
    }
    const actionData = { url: '/base/action/user/update/sip', method: 'POST', data: { loginType, loginNumber } }
    CommonModule.publicAction(actionData).then(res => {
      let form = storageManager.get('loginForm')
      form = form && form !== 'undefined' && form !== 'null' ? JSON.parse(form) : {}
      form.loginType = loginType
      storageManager.set('loginForm', JSON.stringify(form))
      window.sessionStorage.setItem('sessionForm', JSON.stringify(form))
    })
  }

  private logout () { // 退出登录
    const actionData = { url: '/auth/logout', method: 'POST', data: { toAnswerOffline: this.form.toAnswerOffline ? '1' : '0' } }
    CommonModule.publicAction(actionData).then(res => {
      if (res && res.success) {
        window.localStorage.setItem('logoutObj', JSON.stringify(this.form))
        CommonModule.setIsSignOut() // 主动退出的标识，用于onbeforeunload的时候，不提醒
        if (this.getWebRtcFun) { // 注销webrtc
          this.getWebRtcFun.unregister()
          LoginModule.setWebRtcFun(null)
        }
        this.$router.push({ path: '/login' })
        window.location.reload()
      }
    })
  }

  private open () { // 每次点开的时候，拉取最新的座席可选择的sip号列表
    const actionData = { url: '/call/action/general/query', method: 'POST', data: { types: ['availableSipNumberList'] } }
    CommonModule.publicAction(actionData).then(res => {
      if (res && res.success) {
        const resList = res.availableSipNumberList || []
        if (this.sipNumber) {
          resList.unshift({ number: this.sipNumber }) // 获取已注册未绑定的数据列表 加上 座席身上绑定过的号码
        }
        this.sipArr = resList
        this.showDropdrow = true
      }
    })
  }

  private clickFun (e) {
    if (!this.$el.contains(e.target)) {
      this.showDropdrow = false
    }
  }

  get getUserMobile () { // 获取当前座席的手机号
    const user = this.$store.state.common.session.user
    return user ? user.mobile : '--'
  }

  get getWebRtcFun () {
    return this.$store.state.login.webRtcFun
  }

  private beforeMount () {
    let localForm = storageManager.get('loginForm')
    localForm = localForm && localForm !== 'undefined' && localForm !== 'null' ? JSON.parse(localForm) : {}
    this.callType = localForm.loginType
    let logoutForm = storageManager.get('logoutObj')
    logoutForm = logoutForm && logoutForm !== 'undefined' && logoutForm !== 'null' ? JSON.parse(logoutForm) : {}
    this.form = logoutForm
    const user = this.$store.state.common.session.user
    this.limits = user.limits ? user.limits : []
    this.sipNumber = user.sipNumber || ''
    if (user.type === 1 || user.type === 2) { // 1 是超级管理员 2是计费跳转
      this.isAdmin = true
    }
    this.$getCache('/im-center/action/webchat/cache', ['globalConfig'], true).then((res: any) => {
      if (res.globalConfig) {
        this.globalConfig = res.globalConfig[0]
      }
    })
    document.addEventListener('click', this.clickFun)
  }

  private beforeDestroy () {
    document.removeEventListener('click', this.clickFun)
  }

  private autoStateChange (state: boolean): void {
    WebPhoneSdk.CallConfig.autoAnswer = state
  }
}
</script>
<style scoped lang="stylus">
$answer-color = #767E91
.autoAnswer-btn
  .tit
    margin-right 5px
  .text
    margin-left 8px
    color $answer-color
.drop-down-user
  min-width 220px
  min-height 102px
  background #fff
  box-shadow 0px 4px 29px 0px rgba(155, 165, 172, 0.46)
  border-radius 4px
  position absolute
  top 50px
  left 6px
  z-index 100
  li
    color $fc-gray2
    font-size 12px
    border-top 1px solid $border-main
    &:first-child
      border-top 0
    .li-contain
      padding 16px
    .V7_iconfont
      color $icon-gray
      font-size 14px
      padding-right 6px
      vertical-align middle
    .equipment
      color $c-main
      background $bgc-gray
      font-size 12px
      padding 2px
      padding 3px 6px
      border-radius 4px
      margin-right 6px
    .drop-span
      width 52px
      text-align right
      display inline-block
      margin-right 5px
    .call-type-wrap
      margin 12px 0
    .label-wrap
      width 100%
.admin-user
  min-width 130px
  min-height 50px
</style>
